﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using System.Reactive.Linq;
using System.Diagnostics.Contracts;

namespace IdComLog.Reactive
{
    /// <summary>
    /// Provides extension methods for logging in Rx.
    /// </summary>
    public static class RxLogging
    {
        /// <summary>
        /// Logs any exceptions to Log4Net.
        /// </summary>
        /// <typeparam name="T">The type of observable.</typeparam>
        /// <param name="src">The source observable.</param>
        /// <param name="logName">The name to log under.</param>
        /// <returns>An observable which logs any exceptions.</returns>
        public static IObservable<T> LogExceptions<T>(this IObservable<T> src, string logName)
        {
            Contract.Requires(src != null);
            Contract.Requires(logName != null);
            Contract.Ensures(Contract.Result<IObservable<T>>() != null);

            ILog log = LogManager.GetLogger(logName);

            if (!log.IsErrorEnabled)
            {
                return src;
            }

            return src.Catch<T, Exception>(ex =>
            {
                log.Error(ex.Message, ex);
                return Observable.Throw<T>(ex);
            });
        }
    }
}
